package orch

import (
	"fmt"
	"github.com/fatih/color"
	"github.com/hashicorp/hcl/v2"
	"github.com/ihaiker/tfwrapper/internal/config"
	"github.com/ihaiker/tfwrapper/internal/util"
)

func Validate(cfg *config.Wrapper) (FlowPlan, hcl.Diagnostics) {
	steps := make([]*Step, 0)
	for _, file := range cfg.Stack.Files {
		for _, module := range file.Modules {
			steps = append(steps, &Step{
				Name:      module.Name,
				DependsOn: util.RemovePrefix(module.DependsOn, "module."),
				Range:     module.Range,
			})
		}
	}
	flow := newFlow(steps)
	diags := hcl.Diagnostics{}
	//检查循环依赖
	for _, sp := range flow.HasCycle() {
		diags = diags.Append(&hcl.Diagnostic{
			Severity: hcl.DiagError,
			Summary:  "Circular dependency",
			Detail: fmt.Sprintf("%s depends on %s",
				color.HiGreenString(sp.Name),
				util.Color(color.FgHiRed, sp.DependsOn)),
			Subject: &sp.Range,
		})
	}
	//检查module是否存在
	for _, group := range flow {
		for _, step := range group {
			for _, name := range step.DependsOn {
				if _, module := cfg.FindModule(name); module == nil {
					diags = diags.Append(&hcl.Diagnostic{
						Severity: hcl.DiagError,
						Summary:  "Module not found",
						Detail: fmt.Sprintf("Dependent module %s not found in module %s",
							color.HiRedString(name), color.HiRedString(step.Name)),
					})
				}
			}
		}
	}
	return flow, diags
}
